using System;
using System.Windows.Forms;

namespace TangHotKey
{
    /// <summary>
    /// 全局热键静态类，提供简单易用的API
    /// </summary>
    public static class GlobalHotKey
    {
        private static HotKeyManager _manager;
        private static Form _defaultForm;

        /// <summary>
        /// 初始化全局热键管理器
        /// </summary>
        /// <param name="form">用于接收热键消息的窗体</param>
        public static void Initialize(Form form)
        {
            if (_manager != null)
            {
                _manager.Dispose();
            }
            
            _defaultForm = form ?? throw new ArgumentNullException(nameof(form));
            _manager = new HotKeyManager(_defaultForm);
        }

        /// <summary>
        /// 注册热键
        /// </summary>
        /// <param name="modifiers">修饰键</param>
        /// <param name="key">主键</param>
        /// <param name="callback">回调函数</param>
        /// <param name="description">描述</param>
        /// <returns>热键ID，失败返回-1</returns>
        public static int Register(HotKeyManager.ModifierKeys modifiers, Keys key, Action callback, string description = "")
        {
            if (_manager == null)
                throw new InvalidOperationException("请先调用Initialize方法初始化热键管理器");
            
            return _manager.RegisterHotKey(modifiers, key, callback, description);
        }

        /// <summary>
        /// 注销热键
        /// </summary>
        /// <param name="hotKeyId">热键ID</param>
        /// <returns>是否成功</returns>
        public static bool Unregister(int hotKeyId)
        {
            if (_manager == null)
                return false;
            
            return _manager.UnregisterHotKey(hotKeyId);
        }

        /// <summary>
        /// 获取所有已注册的热键信息
        /// </summary>
        /// <returns>热键信息列表</returns>
        public static System.Collections.Generic.List<HotKeyManager.RegisteredHotKeyInfo> GetRegisteredHotKeys()
        {
            if (_manager == null)
                return new System.Collections.Generic.List<HotKeyManager.RegisteredHotKeyInfo>();
            
            return _manager.GetRegisteredHotKeys();
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public static void Cleanup()
        {
            _manager?.Dispose();
            _manager = null;
            _defaultForm = null;
        }

        /// <summary>
        /// 检查是否已初始化
        /// </summary>
        public static bool IsInitialized => _manager != null;
    }
}